package logic

import (
	"context"
	"fmt"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/guid"
	"io"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"torchsr/internal/types"
	"torchsr/task_process"
	"torchsr/utils"

	"github.com/zeromicro/go-zero/core/logx"
	"torchsr/internal/svc"
)

type UploadFileLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUploadFileLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadFileLogic {
	return &UploadFileLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UploadFileLogic) UploadFile(r *http.Request) (resp *types.UploadFileResp, err error) {
	// todo: add your logic here and delete this line

	file, header, err := r.FormFile("file")
	if err != nil {
		fmt.Println("上传文件失败")
		return
	}
	defer file.Close()

	fmt.Println(header.Filename)

	fmt.Println(file)
	// header.Filename 是上传的文件名
	// file 是文件的内容，你可以将其保存到你需要的地方
	taskGuid := guid.S()

	dir := filepath.Join(g.Cfg().GetString("dir_path"), taskGuid)
	//如果没有就创建
	if _, err := os.Stat(dir); os.IsNotExist(err) {
		err := os.MkdirAll(dir, 0755)
		if err != nil {
			// handle error
		}
	}

	// 指定保存的文件路径
	filePath := filepath.Join(dir, header.Filename)

	//保存到本地

	out, err := os.Create(filePath)
	if err != nil {
		fmt.Println("保存文件失败")
		return
	}
	defer out.Close()

	// 将上传的文件内容写入到新文件中
	_, err = io.Copy(out, file)
	if err != nil {
		fmt.Println("保存文件失败")

		return
	}

	fmt.Println("filePath:", filePath)

	fmt.Println("上传文件成功")

	utils.SetTaskGuidToRedis(taskGuid, utils.QUEUED)
	task_process.AddTorchSRTo3DModel(taskGuid, filePath)

	//pythonPath := g.Cfg().GetString("python_path")
	//script := g.Cfg().GetString("script_file")
	//
	//outputPath := g.Cfg().GetString("dir_path")
	//outPutDir := filepath.Join(outputPath, taskGuid)
	//
	//args := []string{script, filePath, "--output-dir", outPutDir, "--render"}
	//
	//outputC, err := exec.Command(pythonPath, args...).Output()
	//if err != nil {
	//	fmt.Println(err)
	//}
	//fmt.Println(string(outputC))
	filePath = strings.Replace(filePath, "\\", "/", -1)
	url := g.Cfg().GetString("dir_url")
	filePathUrl := strings.Replace(filePath, g.Cfg().GetString("dir_path"), url+"/ret_file", 1)

	return &types.UploadFileResp{Status: "ok", Message: "上传成功", TaskId: taskGuid, FilePath: filePathUrl}, nil
}
